//
//  FinancialRecordViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/19.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "FinancialRecordViewController.h"

#import "FinancialContentViewController.h"

#define leftMargin jisuan(62)
#define labelMargin jisuan(66)

@interface FinancialRecordViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) UILabel *moneyL;

@property (strong, nonatomic) UIView *headerView;
@property (strong, nonatomic) UIView *containerView;
@property (strong, nonatomic) UIScrollView *titleScrollView;
@property (strong, nonatomic) UIView *sliderView;
@property (strong, nonatomic) UIScrollView *contentScrollView;

@property (assign, nonatomic) CGFloat labelTotolWidth;
@property (strong, nonatomic) NSArray *arr;
@property (strong, nonatomic) NSMutableArray *labelArr;
@property (strong, nonatomic) NSMutableArray *labelxArr;

@end

@implementation FinancialRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.font = [UIFont boldSystemFontOfSize:jisuan(32)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"财务记录";
    self.navigationItem.titleView = titleLabel;
    
    UIButton*btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, jisuan(18), jisuan(32));
    //nav_go_white  whiteNavBG
    [btn setBackgroundImage:[UIImage imageNamed:@"nav_go_white"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"nav_go_white"] forState:UIControlStateSelected];
    [btn setBackgroundImage:[UIImage imageNamed:@"nav_go_white"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(goBackAction)forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
    
    [self setupTop];
    [self createUI];
    
    [self createScrollView];
    [self createContentVCs];
    
    [self.view layoutIfNeeded];
    
    [self setDefaultTitleAndChildVC];

}

- (void)setDefaultTitleAndChildVC {
    
    UILabel *defaultLabel = self.labelArr[self.type];
    defaultLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(24)];
    
    [self.titleScrollView addSubview:self.sliderView];
    UILabel *label = self.titleScrollView.subviews[self.type];
    self.sliderView.frame = CGRectMake([self.labelxArr[self.type] floatValue], jisuan(100), label.width, jisuan(4));
    
    FinancialContentViewController *vc = self.childViewControllers[self.type];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    vc.view.frame = CGRectMake(WIDTH * self.type, 0, WIDTH, self.contentScrollView.height);
    self.contentScrollView.contentOffset = CGPointMake(WIDTH * self.type, 0);
    [self.contentScrollView addSubview:vc.view];
    
}

- (void)goBackAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -label点击事件
- (void)labelGestureClick:(UIGestureRecognizer *)recognizer {
    
    UILabel *label = (UILabel *)recognizer.view;
    
    [self.contentScrollView setContentOffset:CGPointMake(WIDTH * label.tag, 0) animated:YES];
    
    NSArray *arr = [self.labelArr copy];
    
    for (int i = 0 ; i < [arr count]; i ++) {
        
        UILabel *temp = self.titleScrollView.subviews[i] ;
        
        temp.font = Font(24);
        
    }
    
    label.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(28)];
    
    CGFloat width = self.titleScrollView.frame.size.width;
    CGFloat offsetX = label.center.x - width * 0.5;
    // 最大偏移量
    CGFloat maxOffsetx = self.titleScrollView.contentSize.width - width;
    
    NSLog(@"%.2f\n%.2f", self.titleScrollView.contentSize.width, width);
    if (offsetX < 0) {
        offsetX = 0;
    } else if (offsetX > maxOffsetx) {
        offsetX = maxOffsetx;
    }
    
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    
    CGFloat x = [self.labelxArr[label.tag] floatValue];
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = weakSelf.sliderView.frame;
        rect.origin.x = x;
        rect.size.width = label.width;
        weakSelf.sliderView.frame = rect;
    }];
}

#pragma mark -scrollviewDelegate

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / WIDTH;
    
    FinancialContentViewController *vc = self.childViewControllers[index];
    
    UILabel *label = self.titleScrollView.subviews[index];
    
    for (int i = 0; i < self.labelArr.count;  i ++) {
        
        UILabel *temp = self.labelArr[i];
        temp.font = Font(24);
    }
    
    label.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(28)];;
    
    CGFloat width = self.titleScrollView.frame.size.width;
    CGFloat offsetX = label.center.x - width * 0.5;
    // 最大偏移量
    CGFloat maxOffsetx = self.titleScrollView.contentSize.width - width;
    if (offsetX < 0) {
        offsetX = 0;
    } else if (offsetX > maxOffsetx) {
        offsetX = maxOffsetx;
    }
    
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    
    // 如果子控制器的view已经在上面,就直接返回
    if (vc.view.superview) {
        [vc.view removeFromSuperview];
    }
    
    // 添加
    CGFloat vcW = scrollView.frame.size.width;
    CGFloat vcH = scrollView.frame.size.height;
    CGFloat vcY = 0;
    CGFloat vcX = index * vcW;
    vc.view.frame = CGRectMake(vcX, vcY, vcW, vcH);
    [scrollView addSubview:vc.view];
    
}

- (void)setupTop {
    
    UIView *headerView = [[UIView alloc] init];
    self.headerView = headerView;
    headerView.backgroundColor = WhiteColor;
     CGFloat topHeight = (IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) ? jisuan(430) : jisuan(408);
    headerView.frame = CGRectMake(0, 0, WIDTH, topHeight);
    [self.view addSubview:headerView];
    
    UIImageView *headerBG = [[UIImageView alloc] init];
    headerBG.image = [UIImage imageNamed:@"financialHeaderbg"];
    [headerView addSubview:headerBG];
    [headerBG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerView.mas_top);
        make.centerX.mas_equalTo(headerView.mas_centerX);
        make.width.mas_equalTo(jisuan(750));
         CGFloat topHeight = (IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) ? jisuan(408) : jisuan(392);
        make.height.mas_equalTo(topHeight);
    }];
    
    UIImageView *numBgIV = [[UIImageView alloc] init];
    numBgIV.contentMode = UIViewContentModeScaleAspectFit;
    numBgIV.image = [UIImage imageNamed:@"financialTotolMoneyBG"];
    [headerView addSubview:numBgIV];
    [numBgIV mas_makeConstraints:^(MASConstraintMaker *make) {

        make.bottom.mas_equalTo(headerBG.mas_bottom).with.offset(-jisuan(20));
        make.centerX.mas_equalTo(headerView.mas_centerX);
        make.width.mas_equalTo(jisuan(726));
        make.height.mas_equalTo(jisuan(214));

    }];

    UILabel *balanceL = [[UILabel alloc] init];
    balanceL.text = @"总余额";
    balanceL.textAlignment = NSTextAlignmentLeft;
    balanceL.textColor = Color999999;
    balanceL.font = Font(24);
    [headerView addSubview:balanceL];
    [balanceL mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(numBgIV.mas_left).with.offset(jisuan(30));
        make.top.mas_equalTo(numBgIV.mas_top).with.offset(jisuan(30));
    }];

    UILabel *moneyL = [[UILabel alloc] init];
    self.moneyL = moneyL;
//    NSString *str = @"64.69元";
    NSString *str = [NSString stringWithFormat:@"%@元", [CommonUserInfo sharedInstance].balance];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attributeStr addAttribute:NSFontAttributeName value:Font(60) range:NSMakeRange(0, str.length - 1)];
    [attributeStr addAttribute:NSFontAttributeName value:Font(24) range:NSMakeRange(str.length - 1, 1)];
    moneyL.attributedText = attributeStr;

    moneyL.textAlignment = NSTextAlignmentLeft;
    moneyL.textColor = Color1f89ff;
    [moneyL sizeToFit];
    [headerView addSubview:moneyL];
    [moneyL mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(numBgIV.mas_left).with.offset(jisuan(30));
        make.bottom.mas_equalTo(numBgIV.mas_bottom).with.offset(-jisuan(40));
        make.right.mas_equalTo(numBgIV.mas_right).with.offset(-jisuan(30));
    }];

}

- (void)createUI {

    [self.view addSubview:self.containerView];
    [self.view addSubview:self.titleScrollView];
    [self.view addSubview:self.contentScrollView];
    
    __weak typeof(self) weakSelf = self;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.headerView.mas_bottom);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        
    }];
    [self.titleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.containerView.mas_top);
        make.height.mas_equalTo(jisuan(128));
        
    }];
    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.titleScrollView.mas_bottom);
        make.bottom.mas_equalTo(weakSelf.containerView.mas_bottom);
        
    }];
    
}

#pragma mark -分类标题scrollview布局
- (void)createScrollView {
    
    self.labelTotolWidth = leftMargin;
    
    for (int i = 0; i < self.arr.count; i ++) {
        
        UILabel *label = [[UILabel alloc] init];
        label.tag = i;
        label.userInteractionEnabled = YES;
        label.text = self.arr[i];
        label.font = Font(24);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = Color333333;
        [label sizeToFit];
        [self.labelArr addObject:label];
        
        if (i == 0) {
            
        }else {
            
            UILabel *tempL = self.labelArr[i - 1];
            CGFloat width = tempL.size.width + jisuan(16);
            self.labelTotolWidth = self.labelTotolWidth + width+ labelMargin;
            
        }
        
        [self.labelxArr addObject:[NSString stringWithFormat:@"%.2f",self.labelTotolWidth]];
        
        label.frame = CGRectMake(self.labelTotolWidth, 0, label.size.width + jisuan(16), jisuan(128));
        [self.titleScrollView insertSubview:label atIndex:i];
        
        UITapGestureRecognizer *labelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelGestureClick:)];
        [label addGestureRecognizer:labelGesture];
        
    }
    
    
//    UILabel *firstL = self.labelArr.firstObject;
//    firstL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(28)];
    
    UILabel *temp = [self.labelArr lastObject];
    CGFloat scrollviewWith = self.labelTotolWidth + leftMargin + temp.width;
    CGSize size = CGSizeMake(scrollviewWith, 0);
    
    if (scrollviewWith > WIDTH) {
        
        self.titleScrollView.contentSize = size;
        
    }else {
        
        self.titleScrollView.contentSize = CGSizeMake(WIDTH, 0);
    }
    
    
//    [self.titleScrollView addSubview:self.sliderView];
//    UILabel *label = [self.titleScrollView.subviews firstObject];
//    self.sliderView.frame = CGRectMake([self.labelxArr.firstObject floatValue], jisuan(100), label.width, jisuan(4));

}

#pragma mark -子控制器
- (void)createContentVCs {
    
    for (int i = 0; i < self.labelArr.count; i ++) {
        
        FinancialContentViewController *contentVC = [[FinancialContentViewController alloc] init];
        
        contentVC.tradeType = i + 1;
        [self addChildViewController:contentVC];
    
    }
    
//    FinancialContentViewController *vc = self.childViewControllers.firstObject;
//    
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    vc.view.frame = self.contentScrollView.bounds;
//    [self.contentScrollView addSubview:vc.view];
    
    self.contentScrollView.contentSize = CGSizeMake(WIDTH * self.childViewControllers.count, 0);
    
}

#pragma mark -lazy
- (UIView *)containerView {
    
    if (!_containerView) {
        
        _containerView = [[UIView alloc] init];
        _containerView.backgroundColor = WhiteColor;
    }
    
    return _containerView ;
}

- (UIScrollView *)titleScrollView {
    
    if (!_titleScrollView) {
        
        _titleScrollView = [[UIScrollView alloc] init];
        _titleScrollView.backgroundColor = WhiteColor;
        
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        
        if (@available(iOS 11.0, *)) {
            
            _titleScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
        }
        
        
    }
    
    return _titleScrollView ;
    
}

- (UIView *)sliderView {
    
    if (!_sliderView) {
        
        _sliderView = [[UIView alloc] init];
        _sliderView.backgroundColor = Colorff0000;
        
    }
    
    return _sliderView;
    
}

- (UIScrollView *)contentScrollView {
    
    if (!_contentScrollView) {
        
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.backgroundColor = WhiteColor;
        
        _contentScrollView.showsVerticalScrollIndicator = NO;
//        _contentScrollView.showsHorizontalScrollIndicator = NO;
    
        _contentScrollView.delegate = self;
        _contentScrollView.pagingEnabled = YES;
        _contentScrollView.bounces = NO;
        _contentScrollView.scrollEnabled = NO;
        
        if (@available(iOS 11.0, *)) {
            
            _contentScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
        }
        
        
    }
    
    return _contentScrollView ;
    
}

- (NSArray *)arr {
    
    if (!_arr) {
        
        _arr = @[@"全部", @"提现", @"充值", @"购买"];
    }
    
    return _arr;
    
}

- (NSMutableArray *)labelArr {
    
    if (!_labelArr) {
        
        _labelArr = [NSMutableArray array];
    }
    
    return _labelArr;
}
- (NSMutableArray *)labelxArr {
    
    if (!_labelxArr) {
        
        _labelxArr = [NSMutableArray array];
    }
    
    return _labelxArr;
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBar.translucent = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
